package com.hspedu.ticket;

/**
 * @author DL5O
 * @version 1.0
 * 使用多线程，模拟三个窗口同时售票
 * 总票数 100 张
 */
public class SellTicket {
    public static void main(String[] args) {
        //第一种方式
        //测试
        /*SellTicket01 sellTicket01 = new SellTicket01();
        SellTicket01 sellTicket02 = new SellTicket01();
        SellTicket01 sellTicket03 = new SellTicket01();

        sellTicket01.start();
        sellTicket02.start();
        sellTicket03.start();*/

        System.out.println("===使用接口的方式来售票===");
        SellTicket02 sellTicket02 = new SellTicket02();
        Thread thread1 = new Thread(sellTicket02);
        Thread thread2 = new Thread(sellTicket02);
        Thread thread3 = new Thread(sellTicket02);
        thread1.start();//第一个线程-窗口
        thread2.start();//第二个线程-窗口
        thread3.start();//第三个线程-窗口
    }
}


//使用第一种继承thread的方式
class SellTicket01 extends Thread{
    private static int ticketNum = 100;//让多个线程共享 ticketNum
    @Override
    public void run() {
        while (true){
            if (ticketNum <= 0){
                System.out.println("售票结束..");
                break;
            }
            //休眠50毫秒
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("窗口 " + Thread.currentThread().getName()
                    + " 售出一张票" + "剩余票数=" + (--ticketNum));
        }
    }
}

//实现接口的方式
class SellTicket02 implements Runnable{
    private int ticketNum = 100;

    @Override
    public void run() {
        while (true){
            if (ticketNum <= 0){
                System.out.println("售票结束..");
                break;
            }
            //休眠50毫秒
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("窗口 " + Thread.currentThread().getName()
                    + " 售出一张票" + "剩余票数=" + (--ticketNum));
        }
    }
}
